var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
const { authMiddleware, handleAuthError } = require('./middleware/auth');

// swagger
const swaggerJSDoc = require('swagger-jsdoc');
const swaggerUI = require('swagger-ui-express');


// Swagger 配置
const swaggerOptions = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: 'CRUD API 文档',
      version: '1.0.0',
      description: '简单的 CRUD 接口文档',
    },
    servers: [{ url: 'http://localhost:3000' }],
    components: {
      securitySchemes: {
        BearerAuth: {
          type: 'http',
          scheme: 'bearer',
          bearerFormat: 'JWT', // 可选，明确说明使用 JWT
          description: '输入 JWT Token，格式：Bearer <token>',
        },
      },
      schemas: {
        Comment: {
          type: 'object',
          properties: {
            id: { type: 'integer', example: 1 },
            post_id: { type: 'integer', example: 123 },
            user_id: { type: 'integer', example: 456 },
            content: { type: 'string', example: '精彩内容' },
            likes: { type: 'integer', example: 5 },
            created_at: { type: 'string', format: 'date-time' },
            updated_at: { type: 'string', format: 'date-time' }
          }
        },
        Pagination: {
          type: 'object',
          properties: {
            page: { type: 'integer', example: 1 },
            limit: { type: 'integer', example: 10 },
            total: { type: 'integer', example: 100 },
            totalPages: { type: 'integer', example: 10 }
          }
        }
      },
      parameters: {
        pageParam: {
          in: 'query',
          name: 'page',
          schema: { 
            type: 'integer',
            minimum: 1,
            default: 1
          },
          description: '页码'
        },
        limitParam: {
          in: 'query',
          name: 'limit',
          schema: { 
            type: 'integer',
            minimum: 1,
            maximum: 100,
            default: 10
          },
          description: '每页数量'
        }
      }
    }
  },
  apis: ['./routes/*.js'], // 指定路由文件路径（扫描注释）
};

const swaggerSpec = swaggerJSDoc(swaggerOptions);

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var postRouter = require('./routes/posts');
var commentRouter = require('./routes/comments');
var characterRouter = require('./routes/character');
var uploadRouter = require('./routes/upload');
var characterCommentRouter = require('./routes/character_comment');

var app = express();


app.use(cors({
  origin: 'http://localhost:5173' // 只允许前端地址访问
}));

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(authMiddleware);
app.use(handleAuthError);


app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/posts', postRouter);
app.use('/uploads', uploadRouter);
app.use('/comments', commentRouter);
app.use('/character_comment', characterCommentRouter)
app.use('/characters', characterRouter);
app.use('/api-docs', swaggerUI.serve, swaggerUI.setup(swaggerSpec));

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
module.exports = app;
